<?php

namespace Mouta\AmistateBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\DependencyInjection;

use Mouta\AmistateBundle\utils\SfGoogleMaps;
use Mouta\AmistateBundle\utils\Strings;
use Mouta\AmistateBundle\Entity\Usuario;
use Mouta\AmistateBundle\Entity\ImagenUsuario;


class EditPerfilController extends Controller
{
    public function mostrarAquiAction(){
        $user = $this->get('security.context')->getToken()->getUser();
        if(!$user->getVerificado())
            return new Response(json_encode( array('valid'=>false,'mensaje'=>'Usted va a aparece aquí en breve') ));
        $user->setEnHeaderAt( date_create_from_format('d/m/Y', date('d/m/Y')) );
        $em = $this->getDoctrine()->getEntityManager();
        $em->persist($user);
        $em->flush();
        return new Response(json_encode( array('valid'=>true) ));
    }
    
    public function UbicacionAction($name = "ubicacion_google"){
        $request = $this->getRequest();
        $term = $request->get('term');
        if(is_null($term))
        {
            return $this->render('AmistateBundle:editPerfil:ubicacion.html.twig',array(
                'ubicacion_text'=>$request->get('ubicacion_text'),
                'pais'=>$request->get('control_u_pais'),
                'provincia'=>$request->get('control_u_provincia'),
                'ciudad'=>$request->get('control_u_ciudad'),
                'latitude'=>$request->get('control_u_latitude'),
                'longitude'=>$request->get('control_u_longitude'),
                'name'=>$name,
            ));
            
        }else{
            return new Response(json_encode(SfGoogleMaps::executeGetLocalidades($term)));
        }
    }
    
    public function ImagenDefaultAction($imagen){
        $user = $this->get('security.context')->getToken()->getUser();
        $em = $this->getDoctrine()->getEntityManager();
        $imagenes = $em->getRepository('AmistateBundle:ImagenUsuario')->findBy(array('usuario'=>$user->getId()));
        foreach($imagenes as $img){
            if($imagen == $img->getId()){
                $img->setDefa(1);
                $em->persist($img);
            }elseif($img->getDefa()){
                $img->setDefa(0);
                $em->persist($img);
            }
        }
        $em->flush();
        die;
    }
    
    public function ImagenDeleteAction($imagen){
        $user = $this->get('security.context')->getToken()->getUser();
        $em = $this->getDoctrine()->getEntityManager();
        $imagen = $em->getRepository('AmistateBundle:ImagenUsuario')->findOneBy(array('id'=>$imagen));
        if($imagen && ( $imagen->getUsuario()->getId()==$user->getId() ) ){
            $em->remove($imagen);
            $em->flush();
            if(is_file($imagen->getPathImage().$imagen->getImagen()))
                unlink ($imagen->getPathImage().$imagen->getImagen());
            if(is_file($imagen->getPathImage().$imagen->getImagenBig()))
                unlink ($imagen->getPathImage().$imagen->getImagenBig());
            
        }
        $em->getRepository('AmistateBundle:ImagenUsuario')->actualizarDefault($user->getId());
        die;
    }
    
    public function ImagenSaveAction(){
        $imagen = $this->getRequest()->get('imagen');
        $label = $this->getRequest()->get('label');
        $user = $this->get('security.context')->getToken()->getUser();
        $em = $this->getDoctrine()->getEntityManager();
        $imagen = $em->getRepository('AmistateBundle:ImagenUsuario')->findOneBy(array('id'=>$imagen));
        if($imagen && ( $imagen->getUsuario()->getId()==$user->getId() ) ){
            $imagen->setLabel($label);
            $user->setVerificado(0);
            $em->persist($user);
            $em->persist($imagen);
            $em->flush();
        }
        die;
    }
    
    public function ImagenUploadAction(){
        $usuario = $this->get('security.context')->getToken()->getUser();
        $em = $this->getDoctrine()->getEntityManager();
        $errorMaxImage = "";
        if( count($usuario->getImagenes()) >= ImagenUsuario::MAXIMAGES)
            $errorMaxImage = "No puede subir más imagenes";
        
        $request = $this->getRequest();
        $now = date_create_from_format('d/m/Y', date('d/m/Y'));
        $ui = new ImagenUsuario();
        $ui->setUsuario($usuario);
        $ui->setCreatedAt($now);
        $ui->setDefa(0);
        $uploaded = $ui->uploadImagen($request);
        if($uploaded)
        {
            $usuario->setVerificado(0);
            $em->persist($usuario);
            $em->persist($ui);
        }
        $em->flush();
        $em->getRepository('AmistateBundle:ImagenUsuario')->actualizarDefault($usuario->getId());
        return $this->redirect( $this->generateUrl('fos_user_profile_show'));
    }
    
    public function AddFotoAction(){
        $user = $this->get('security.context')->getToken()->getUser();
        return $this->render('AmistateBundle:editPerfil:add_foto.html.twig',array(
                'email'=>  base64_encode($user->getEmail()),
                'clave'=>  base64_encode($user->getPassword()),
                'max_images'=> ImagenUsuario::MAXIMAGES,
            ));
    }
    
    public function EditAction(){
        $user = $this->get('security.context')->getToken()->getUser();
        $em = $this->getDoctrine()->getEntityManager();
        return $this->render('AmistateBundle:editPerfil:base_edit.html.twig',array(
                'user'=>$user,
            ));
    }
    
    public function SaveAction(){
        $request = $this->getRequest();
        if(!$this->get('security.context')->isGranted('ROLE_USER'))
            return false;
        $user = $this->get('security.context')->getToken()->getUser();
        if($request->getMethod() == 'POST' && $request->isXmlHttpRequest() && $user)
        {
            $posts = $request->request->all();
            foreach($posts as $key => $value){
                $key = str_replace('control_', '', $key);
                $key = str_replace('u_', '', $key);
                if($key == 'tab' || $key == 'rclave')
                    continue;
                if($key=='cumple')
                    $value = date_create_from_format('d/m/Y', $value);
                
                if($key=='password')
                    $user->setPlainPassword($value);
                
                $prop = "set".Strings::camelize($key);
                $user->$prop($value);
            }
            $user->setVerificado(0);

            $this->get('amistate.user_manager')->actualizarUser($user);
            
            switch ($request->get('tab')) {
                case 'sobre-mi':
                  return $this->render('AmistateBundle:perfil:sobre_mi.html.twig',array(
                        'user'=>$user,
                        'admin'=>true,
                    ));
                  break;
                case 'vivo':
                  return $this->render('AmistateBundle:perfil:ubicacion.html.twig',array(
                        'user'=>$user,
                        'admin'=>true,
                    ));
                  break;
                case 'busco':
                  return $this->render('AmistateBundle:perfil:busco.html.twig',array(
                        'user'=>$user,
                        'admin'=>true,
                    ));
                  break;
                case 'info-basica':
                  return $this->render('AmistateBundle:perfil:info_basica.html.twig',array(
                        'user'=>$user,
                        'admin'=>true,
                    ));
                  break;
                case 'caracteristicas':
                  return $this->render('AmistateBundle:perfil:caracteristicas.html.twig',array(
                        'user'=>$user,
                        'admin'=>true,
                    ));
                  break;
                case 'preferencias':
                  return $this->render('AmistateBundle:perfil:preferencias.html.twig',array(
                        'user'=>$user,
                        'admin'=>true,
                    ));
                  break;
                case 'nombre':
                    return $this->render('AmistateBundle:perfil:nombre.html.twig',array(
                        'user'=>$user,
                        'admin'=>true,
                    ));
                  break;

                default:
                  break;
              }
        }
        return $this->redirect( $this->generateUrl('_homepage'));
    }
}
